#!/usr/bin/python3
# coding=utf8
import cv2
import time
import threading
import numpy as np
import Camera
import MjpgServer

def startMjpgServerTest():
    """
    启动摄像头并通过 MjpgServer 提供图像流
    """
    # 加载摄像头
    print("Opening camera...")
    cam = Camera.Camera()
    cam.camera_open()

    # 启动 MjpgServer 的线程
    threading.Thread(target=MjpgServer.startMjpgServer, daemon=True).start()
    print("MjpgServer started...")

    # 加载默认的加载图片（防止摄像头未捕获到帧时的空白显示）
    loading_picture = cv2.imread('/home/pi/CameraCalibration/loading.jpg')
    if loading_picture is None:
        print("Loading picture not found, using blank image as fallback.")
        loading_picture = np.zeros((480, 640, 3), dtype=np.uint8)

    try:
        while True:
            time.sleep(0.03)  # 每帧延迟

            # 获取摄像头帧
            frame = cam.frame
            if frame is not None:
                # 在 MJPG 流上显示摄像头的实时帧
                MjpgServer.img_show = frame.copy()
            else:
                # 如果没有图像帧，显示加载图片
                MjpgServer.img_show = loading_picture
    except KeyboardInterrupt:
        print("Exiting...")
    finally:
        cam.camera_close()
        print("Camera closed.")

if __name__ == '__main__':
    startMjpgServerTest()

